package org.wt.phoenix.middleware.springboot.retry.impl;

import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.wt.phoenix.middleware.springboot.retry.RetryService;

import java.time.LocalDateTime;
import java.util.Random;

@Service
public class RetryServiceImpl implements RetryService {

    /**
     * 尝试执行方法，如报错则重试。
     * @param taskName
     * @return
     */
    @Retryable(value = {RetryException.class}, maxAttempts = 3, backoff = @Backoff(delay = 1000, multiplier = 2))
    @Override
    public String tryExecute(String taskName) {
        System.out.println("当前线程：" + Thread.currentThread().getName() + ",tryExecute 任务名称：" + taskName + "，开始执行，当前时间：" + LocalDateTime.now());
        int i = new Random().nextInt() % 2;
        if (i == 0){
            System.out.println("当前线程：" + Thread.currentThread().getName() + ",tryExecute 任务名称：" + taskName + "，出现异常结束，当前时间：" + LocalDateTime.now());
            throw new RetryException("模拟异常");
        }
        System.out.println("当前线程：" + Thread.currentThread().getName() + ",tryExecute 任务名称：" + taskName + "，执行结束，当前时间：" + LocalDateTime.now());
        return taskName;
    }

}
